﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Engine;
using Engine.Result;
using InterfaceService.Testing;

namespace ServiceImp
{
    public class TestingService: ITestingService
    {
        public event EventHandler<TestState> OnTestStateChanged;
        public event EventHandler<ChipResult> OnTestDataReceived;
        public event EventHandler<Exception> OnError;
        public bool IsManualTest { get; set; }
        private bool _isTesting;
        private RunMachine _tester;
        WaferTesterContext _ctx = new WaferTesterContext();
        public void ManualStart(int itemIdx, int testTimes, int testInterval, bool continueLighting)
        {
            throw new NotImplementedException();
        }
         
        public async void Start()
        {
            try
            {
                _isTesting = true;
                OnTestStateChanged?.Invoke(this, TestState.PreStart);
           
                _ctx.OnChipResult += _ctx_OnChipResult;
                _tester = new RunMachine(_ctx);
                
                OnTestStateChanged?.Invoke(this, TestState.Testing);
                await _tester.Run();
                _isTesting = false;
                OnTestStateChanged?.Invoke(this, TestState.PreStop);
                OnTestStateChanged?.Invoke(this, TestState.Stopped);
            }
            catch (Exception e)
            {
                _isTesting = false;
                OnTestStateChanged?.Invoke(this, TestState.PreStop);
                OnTestStateChanged?.Invoke(this, TestState.Stopped);
                OnError?.Invoke(this, e);
            }
        }

        private void _ctx_OnChipResult(object sender, ChipResult e)
        {
            OnTestDataReceived?.Invoke(this, e);
        }

        private void OnThisPassDone(object sender, Engine.Result.ChipResult e)
        {
            OnTestDataReceived?.Invoke(this, e);
        }
        public void Stop()
        {
            _tester?.Stop();
        }

        public void EmitChip()
        {
            while (true)
            {
                _ctx.EmitChip(0);
            }
           
        }
    }
}
